package cp6;

import bean.UserInfo;
import util.Constants;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DataReadTool {
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取所有的用户
     * @return
     * @throws SQLException
     */
    public static List<UserInfo> getAllUser() throws SQLException {
        Connection conn = DriverManager.getConnection(Constants.URL, Constants.USERNAME, Constants.PASSWORD);
        Statement st = conn.createStatement();
        ResultSet rs = st.executeQuery("select * from userinfo");
        //读取数据
        List<UserInfo> userInfoList = new ArrayList<>();
        while (rs.next()) {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(
                    rs.getInt("id")
            );
            userInfo.setNickname(
                    rs.getString("nickname")
            );
            // 将对象添加到集合
            userInfoList.add(userInfo);
        }
        rs.close();
        st.close();
        conn.close();
        return userInfoList;
    }
}
